<template>
  <div class="user-manage-wrapper">
    <table-view
      :cols="cols"
      :tableData="tableData"
      :canCheck="true"
      :showSearch="true"
      :searchCondition="searchCondition"
      :showOperate="true"
      :showPaginator="true"
      :buttonCount="2"
      :clearSelect="clearSelect"
      :pageNumber="pageNumber"
      :pageSize="pageSize"
      :totalRecords="totalRecords"
      :operateButtons="operateButtons"
      @on-operate="clickOperate"
      @on-search="search"
      @selection-change="selectChange"
      @size-change="sizeChange"
      @current-page-change="pageChange"
      @preClick="pageChange"
      @nextClick="pageChange"
    >
      <div class="operate-button-group">
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="showModal('add')">新增</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="showModal('delete')">删除</el-button>
      </div>
    </table-view>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="540px">
      <div class="dialog-container" v-if="dialogTitle === '删除'">您确定要删除这些信息吗？</div>
      <div class="dialog-container" v-else-if="dialogTitle === '重置密码'">
        重置密码后用户的旧密码将不能使用，您确定要重置该用户的密码吗？
      </div>
      <div class="dialog-container" v-else-if="dialogTitle === '修改密码'">
        <form-view class="form-view" :items="editPwdItems" :add-form="value" :labelWidth="'35%'" :valueWidth="'80%'" ref="pwdFormRef"/>
      </div>
      <div class="dialog-container" v-else>
        <form-view class="form-view" :items="dialogItems" :add-form="value" :labelWidth="'200px'" :valueWidth="'80%'" ref="formRef"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="save(dialogTitle)" v-if="showSaveButton">保存</el-button>
        <el-button type="primary" size="small" @click="confirm(dialogTitle)" v-if="!showSaveButton">确定</el-button>
        <el-button size="small" @click="dialogVisible = false" v-show="dialogTitle === '修改密码'">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

  export default {
    name: "user-manage",
    data() {
      let baseUrl = managerRemoteGatewayUrl + "/user";
      return {
        urls: {
          getHeaderUrl: "./static/json/user-manage-header.json",
          getTableDataUrl: baseUrl + "/search", //获取用户列表，查询也可使用
          getUserRoleUrl: baseUrl + "/org/list", //获取用户角色列表
          addUrl: baseUrl + "/add", //新增
          updateUrl: baseUrl + "/edit", //编辑
          deleteUrl: baseUrl + "/delete", //删除
          resetPwdUrl: baseUrl + "/reset/password", //重置密码
          editPwdUrl: baseUrl + "/change/password" //修改密码
        },
        cols: [],
        tableData: [],
        selectedData: [],
        clearSelect: false,
        searchCondition: [],
        pageNumber: 1,
        pageSize: 10,
        totalRecords: 0,
        dialogTitle: "",
        dialogVisible: false,
        showSaveButton: true,
        dialogItems: [],
        operateButtons: ['编辑', '重置密码', '修改密码'],
        currentRow: null,
        userInfo: {},
        editPwdItems: [
          {type: 'password', field: 'oldPwd', header: '旧密码', rule: {required: true}},
          {type: 'password', field: 'newPwd', header: '新密码', rule: {required: true}}
        ],
        value: {},
        searchFilter: {}, // 搜索
      };
    },
    mounted() {
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      this.getInitData();
      this.getTableData();
    },
    methods: {
      //获取表头数据
      getHeader() {
        this.cols = [];
        return new Promise((resolve, reject) => {
          this.httpRequest("get", this.urls.getHeaderUrl, {}, {
            hideEmptyTip: true,
            hideSuccessTip: true,
            ignoreEmptyData: true,
            fullSuccess: true,
            hideErrorTip: true,
          }).then(res => {
            this.cols = res.cols;
            this.searchCondition = [];
            res.cols.forEach(d => {
              if (d.search) {
                let obj = this.cloneObj(d);
                if (d.header.indexOf("时间") !== -1) {
                  let start = this.cloneObj(d);
                  start["label"] = start.header.replace("时间", "开始时间");
                  start["field"] = start.field.replace("time", "timeStart");
                  start["value"] = null;
                  this.searchCondition.push(start);
                  let end = this.cloneObj(d);
                  end["label"] = end.header.replace("时间", "结束时间");
                  end["field"] = end.field.replace("time", "timeEnd");
                  end["value"] = null;
                  this.searchCondition.push(end);
                } else {
                  obj["label"] = d.header;
                  obj["value"] = null;
                  this.searchCondition.push(obj);
                }
              }
            });
            this.searchFilter = this.setFilter(this.searchCondition);
            resolve(res)
          })
        })
      },
      getUserRole() {
        return new Promise(((resolve, reject) => {
          this.httpRequest("get", this.urls.getUserRoleUrl + "?userid=" + this.userInfo.userId, {}, {
            hideEmptyTip: true,
            hideSuccessTip: true,
            fullSuccess: true,
            ignoreEmptyData: true,
            hideErrorTip: true,
          }).then(res => {
            resolve(res.value.all)
          })
        }))
      },
      getInitData() {
        Promise.all([this.getHeader(), this.getUserRole()]).then(res => {
          this.cols.forEach(d => {
            if (d.field === "org") {
              d.option = res[1];
            }
          });
        })
      },
      // 获取表格数据
      getTableData() {
        let param = {
          pageNumber: this.pageNumber,
          pageSize: this.pageSize,
          filter: this.searchFilter
        }
        this.httpRequest("post", this.urls.getTableDataUrl, param, {
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          this.tableData = res.value.data;
          this.totalRecords = res.value.rows;
        })
      },
      // 显示弹框，新增、编辑、删除、重置密码等操作时显示
      showModal(str, data) {
        this.currentRow = data;
        if (str === "add") {
          this.dialogTitle = "新增";
          this.dialogItems = this.getFormItem(this.cols, 'addable')
          this.dialogVisible = true;
          this.showSaveButton = true;
          this.dialogItems.forEach(d => {
            if (d.id === "username") {
              d.disabled = false;
            }
          });
          this.$nextTick(() => {
            this.value = this.getFormData(this.dialogItems)
            this.$refs.formRef.resetFields()
          })
        } else if (str === "edit") {
          this.dialogTitle = "编辑";
          this.showSaveButton = true;
          this.dialogItems = this.getFormItem(this.cols, 'editable');
          console.log("this.dialogItems",this.dialogItems);
          this.dialogVisible = true;
          console.log("this.currentRow",this.currentRow);
          this.$nextTick(() => {
            this.$refs.formRef.resetFields();
            this.value = this.getEditFormData(this.dialogItems, data);
            console.log("编辑",this.value);
          })
        } else if (str === "delete") {
          if (this.selectedData.length <= 0) {
            this.$message.warning("请至少选择一项进行删除！");
            return;
          }
          this.dialogTitle = "删除";
          this.dialogVisible = true;
          this.showSaveButton = false;
        } else if (str === "resetPwd") {
          this.dialogTitle = "重置密码";
          this.dialogVisible = true;
          this.showSaveButton = false;
        } else if (str === 'editPwd') {
          this.dialogTitle = "修改密码";
          this.dialogVisible = true;
          this.showSaveButton = false;
          this.$nextTick(() => {
            this.value = this.getFormData(this.editPwdItems)
            this.$refs.pwdFormRef.resetFields()
          })
        }
      },
      // 新增/编辑 保存
      save(title) {
        if (title === "新增") {
          this.$refs.formRef.validate().then(res => {
            this.saveData("add");
          })
        } else if (title === "编辑") {
          this.$refs.formRef.validate().then(res => {
            this.saveData("edit");
          })
        }
      },
      saveData(type) {
        let url = "",
          httpType = "";
        if (type === "add") {
          url = this.urls.addUrl;
          httpType = "post";
        } else if (type === "edit") {
          url = this.urls.updateUrl;
          httpType = "put";
        } else {
          return;
        }
        this.httpRequest(httpType, url, this.value, {
          hasError: true,
          fullSuccess: true,
        }).then(res => {
          this.message(this, "success", res.message);
          this.dialogVisible = false;
          this.getTableData();
        }).catch(err => {
          try {
            if (type === "add") {
              if (err.status === 621) {
                this.message(
                  this,
                  "error",
                  "请求已经被缓存，当服务恢复后会回放此请求"
                );
              } else if (err.status === 650) {
                this.message(this, "error", "缓存服务内部错误");
              } else {
                if (err.data.message) {
                  this.message(this, "error", err.data.message);
                } else {
                  this.message(this, "error", err.message);
                }
              }
            } else {
              if (err.data.message) {
                this.message(this, "error", err.data.message);
              } else {
                this.message(this, "error", err.message);
              }
            }
          } catch (e) {
            this.message(this, "error", "操作失败！");
          }
          this.dialogVisible = false;
        })
      },
      confirm(title) {
        if (title === "删除") {
          this.deleteData();
        } else if (title === "重置密码") {
          this.resetPwd();
        } else if (title === '修改密码') {
          this.$refs.pwdFormRef.validate().then(res => {
            this.editPasswords();
          })
        } else if (title === '提示') {
          this.dialogVisible = false;
        }
      },
      //  删除数据
      deleteData() {
        let me = this;
        me.clearSelect = false;
        let ids = this.selectedData.map(d => {
          return d.id;
        });
        this.httpRequest("delete", this.urls.deleteUrl + "?userid=" + ids.join(","), {}, {
          hasError: true,
          fullSuccess: true,
        }).then(res => {
          me.message(me, "success", res.message);
          me.dialogVisible = false;
          me.pageNumber = 1;
          me.getTableData();
          me.clearSelect = true;
        }).catch(err => {
          me.message(me, "error", err.message);
          me.dialogVisible = false;
        })
      },
      editPasswords() {
        this.value['id'] = this.currentRow.id;
        this.httpRequest("put", this.urls.editPwdUrl, this.value, {
          hideEmptyTip: true,
          hideSuccessTip: true,
          ignoreEmptyData: true,
          fullSuccess: true,
        }).then(res => {
          this.message(this, "success", res.message);
          this.dialogVisible = false;
          this.getTableData();
        })
      },
      // 表格选中项发生改变时，触发的函数
      selectChange(selection) {
        this.selectedData = selection;
      },
      // pageSize更改时，触发的回调
      sizeChange(size) {
        this.pageNumber = 1;
        this.pageSize = size;
        this.getTableData();
      },
      // 上一页、下一页等改变pageNumber时的回调
      pageChange(page) {
        this.pageNumber = page;
        this.getTableData();
      },
      // 重置密码
      resetPwd() {
        let me = this;
        this.httpRequest("put", this.urls.resetPwdUrl + "?userid=" + me.currentRow.id, {}, {
          fullSuccess: true,
        }).then(res => {
          me.message(me, "success", res.message);
          me.dialogVisible = false;
        }).catch(err => {
          me.message(me, "error", err.message);
          me.dialogVisible = false;
        })
      },
      clickOperate(e) {
        switch (e.btnText) {
          case '编辑':
            this.showModal('edit', e.row)
            break;
          case '重置密码':
            this.showModal('resetPwd', e.row)
            break;
          case '修改密码':
            this.showModal('editPwd', e.row)
            break;
          default:
            break;
        }
      },
      // 查询
      search(e) {
        let str = "",timeStart = null, timeEnd = null, param = {filter: {}};
        e.forEach(d => {
          if (d.field === "createtimeStart") {
            timeStart = !this.isEmpty(d.value) ? d.value : null;
          } else if (d.field === "createtimeEnd") {
            timeEnd = !this.isEmpty(d.value) ? d.value : null;
          } else {
            if (!this.isEmpty(d.value)) {
              let key = "";
              key = d.field;
              if (d.type == "multiSelect") {
                if (d.value && d.value.length != 0) {
                  param.filter[key] = [d.value];
                }
              } else {
                param.filter[key] = [d.value];
              }
            }
          }
        });
        if (timeStart == null && timeEnd == null) {
        } else {
          param.filter["createtime"] = [timeStart, timeEnd];
        }
        if (!this.isEmpty(str)) {
          this.message(this, "warn", str, true);
          return;
        }
        if (timeStart != null && timeEnd != null) {
          let startTime = new Date(timeStart.replace(/-/g, "/"));
          let endTime = new Date(timeEnd.replace(/-/g, "/"));
          if (startTime >= endTime) {
            this.message(this, "warn", "开始时间必须小于结束时间");
            return;
          }
        }
        this.pageNumber = 1;
        // this.searchFilter = this.setFilter(e);
        this.searchFilter = param.filter;
        this.getTableData();
      }
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  @import "../../../assets/styles/base_style";
  .user-manage-wrapper {
    width: 100%;
    height: 100%;
    .operate-button-group {
      margin-bottom: 10px;
    }
  }
</style>
